package com.gelpag.base.business.menu;

import been.UserInfo;
import com.gelpag.base.init.InitRedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.utils.Common;
import tools.utils.IdWorker;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private MenuMapper menuMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    InitRedisService initRedisService;

    @Autowired
    IdWorker idWorker;

    //根据角色获取菜单
    public List<MenuInfo> getMenuListByRoles(UserInfo userInfo, String sys_code) {

        //1.获取当前角色对应的所有父级菜单
        List<MenuInfo> menuInfoList = menuMapper.getMenuListByRoles(userInfo.getUser_id(), sys_code);

        //2.递归查询，将父级菜单下的子菜单信息加入
        return getMenuChildListByUserId(menuInfoList, userInfo.getUser_id(), sys_code);
    }

    private List<MenuInfo> getMenuChildListByUserId(List<MenuInfo> menu_list, String user_id, String sys_code) {

        if (menu_list != null) {
            //证明有父级菜单
            for (int i = 0; i < menu_list.size(); i++) {

                String menu_id = menu_list.get(i).getMenu_id();

                //step.1 从mysql获取子菜单信息
                List<MenuInfo> childMenuList = menuMapper.getMenuChildListByParentMenuId(menu_id, sys_code);
                if (childMenuList != null) {

                    //step.2 若有子菜单,且当前角色有此子菜单权限,保存到父菜单下
                    List<MenuInfo> childMenu_list_by_user_id = new ArrayList<MenuInfo>();

                    for (int j = 0; j < childMenuList.size(); j++) {

                        //a、 子菜单所对应的角色字符串不为空时,判断当前角色是否有此子菜单权限
                        if (!Common.isNullString(childMenuList.get(j).getRole_user_ids())) {
                            //b、 拆分子菜单对应字符串
                            String[] menu_user_ids = childMenuList.get(j).getRole_user_ids().split(";");
                            boolean flag = false;
                            //c、 判断子菜单所对应的角色中是否包含当前登录角色,包含则添加到list中,用于储存到父菜单bean的子菜单list中
                            for (String menu_user_id : menu_user_ids) {
                                if (menu_user_id.equals(user_id)) {
                                    flag = true;
                                }
                            }
                            if (flag) {
                                childMenu_list_by_user_id.add(childMenuList.get(j));
                            }
                        }
                    }
                    menu_list.get(i).setChildlist(childMenu_list_by_user_id.size() == 0 ? null : childMenu_list_by_user_id);
                    getMenuChildListByUserId(childMenu_list_by_user_id, user_id,sys_code);
                }
            }
        }
        return menu_list;
    }

    //根据系统获取菜单树
    public List<MenuInfo> getMenuTree(String sys_code) {

        //1.获取所有父级菜单
        List<MenuInfo> menuList = menuMapper.getMenuList(sys_code);

        //2.递归查询，将父级菜单下的子菜单加入
        return getMenuChildListResource(menuList, sys_code);
    }

    private List<MenuInfo> getMenuChildListResource(List<MenuInfo> menu_list, String sys_code) {

        for (int i = 0; i<menu_list.size(); i++) {
            String menu_id = menu_list.get(i).getMenu_id();
            //获取子菜单信息
            List<MenuInfo> childMenu_list = menuMapper.getMenuChildListByParentMenuId(menu_id, sys_code);
            if(childMenu_list != null) {
                //若有子菜单，排序并保存到对应的父菜单下
                menu_list.get(i).setChildlist(childMenu_list);
                getMenuChildListResource(childMenu_list, sys_code);
            }
        }
        return menu_list;
    }

    public int getResourceCountByParent_menu_id(String parent_id) {
        return menuMapper.getResourceCountByParent_menu_id(parent_id);
    }

    @Transactional
    public void editMenu(MenuInfo menuInfo) {
        //判断menu_id是否为空（为空是新增，否则修改）
        if (Common.isNullString(menuInfo.getMenu_id())) {
            menuInfo.setMenu_id(idWorker.nextId());
            menuMapper.insertMenu(menuInfo);
        } else {
            menuMapper.updateMenu(menuInfo);
        }
    }

    public MenuInfo getMenuInfoById(String menu_id) {
        return menuMapper.getMenuInfoById(menu_id);
    }

    public List<MenuInfo> getChildMenus(String menu_id) {
        return menuMapper.getChildMenus(menu_id);
    }

    @Transactional
    public void delMenu(String menu_id) {
        menuMapper.delMenu(menu_id);
        //刷新redis权限信息
        initRedisService.initRedis(stringRedisTemplate);
    }

    public List<ResourceInfo> getUrlsByMenuId(String menu_id) {
        return menuMapper.getUrlsByMenuId(menu_id);
    }

    public int getChildMenusByMenuId(String menu_id) {
        return menuMapper.getChildMenusByMenuId(menu_id);
    }

    public void editUrl(ResourceInfo resourceInfo, UserInfo userInfo) {
        String resource_id = resourceInfo.getResource_id();
        resourceInfo.setUp_date(Common.getSysDate("yyyy-MM-dd HH:mm:ss"));
        resourceInfo.setUp_id(userInfo.getUser_id());
        resourceInfo.setUp_name(userInfo.getUp_name());
        if (Common.isNullString(resource_id)) {
            //新增
            resourceInfo.setResource_id(idWorker.nextId());
            resourceInfo.setOp_id(userInfo.getUser_id());
            resourceInfo.setOp_date(Common.getSysDate("yyyy-MM-dd HH:mm:ss"));
            resourceInfo.setOp_name(userInfo.getUser_name());
            menuMapper.insertResourceInfo(resourceInfo);
        }else {
            //修改
            menuMapper.updateResurceInfo(resourceInfo);
        }
    }

    @Transactional
    public void delUrl(String resource_id) {
        //删除资源和角色的对应关系
        menuMapper.delResourceRole(resource_id);
        //删除资源信息
        menuMapper.delUrl(resource_id);
        //刷新Redis权限信息
        initRedisService.initRedis(stringRedisTemplate);
    }
}
